// alibabaApi.js

import { ApiInterface } from "./apiInterface.js";

export class OpenAiApi extends ApiInterface {
  constructor(apiUrl, apiKey, apiVersion) {
    super();
    this.apiUrl = apiUrl;
    this.apiKey = apiKey;
    this.apiVersion = apiVersion;
    this.messages = [];
  }

  // 将题目添加到上下文中
  addQuestionContext(questionContent) {
    this.messages.push({
      role: "system",
      content: `你是一个专业的学习助手，负责回答用户关于各类题目的问题。你会给出清晰、正确的解释，并帮助用户理解题目的核心概念。以下是用户需要解答的题目内容，请将其纳入你的回答上下文中：${questionContent}`,
    });
    return this;
  }

  // 设置请求ID
  setRequestId(requestId) {
    this.requestId = requestId;
    return this;
  }

  // 通过后台脚本发送请求
  async sendRequest(userMessage, onChunk) {
    console.log("sendRequest", userMessage, onChunk);

    // 添加用户消息到对话历史
    this.messages.push({ role: "user", content: userMessage });

    try {
      console.log("请求详情：", {
        apiUrl: this.apiUrl,
        apiKey: this.apiKey ? "已设置 (隐藏)" : "未设置",
        apiVersion: this.apiVersion,
        messagesCount: this.messages.length,
      });

      // 使用设置的请求ID或生成新的
      const requestId = this.requestId || Date.now().toString();

      // 发送请求到后台脚本
      console.log(
        `[${new Date().toISOString()}] 开始发送请求，ID: ${requestId}`
      );
      browser.runtime
        .sendMessage({
          type: "alibabaApiRequest",
          requestId: requestId,
          apiUrl: this.apiUrl,
          apiKey: this.apiKey,
          apiVersion: this.apiVersion,
          messages: this.messages,
        })
        .then(() => {
          console.log(
            `[${new Date().toISOString()}] 请求已成功发送到后台脚本，ID: ${requestId}`
          );
        })
        .catch((error) => {
          console.error(
            `[${new Date().toISOString()}] 发送请求时出现错误，ID: ${requestId}`,
            error
          );
          reject(error);
        });

      // 通过消息传递给background script处理API请求
      return new Promise((resolve, reject) => {
        // 设置请求超时
        const requestTimeout = setTimeout(() => {
          browser.runtime.onMessage.removeListener(messageListener);
          reject(new Error("请求超时，未收到后台脚本响应"));
        }, 30000); // 30秒超时

        // 创建一个消息处理函数来接收流式响应
        const messageListener = (message) => {
          // 收到任何响应都清除超时
          if (message.requestId === requestId) {
            clearTimeout(requestTimeout);
          }

          if (
            message.type === "alibabaApiRequestReceived" &&
            message.requestId === requestId
          ) {
            console.log(
              `[${new Date().toISOString()}] 后台脚本已接收请求，ID: ${requestId}`
            );
            // 可以在这里更新UI状态
          } else if (
            message.type === "alibabaApiStreamChunk" &&
            message.requestId === requestId
          ) {
            // 处理流式响应块
            if (onChunk && typeof onChunk === "function") {
              onChunk(message.chunk);
            }
          } else if (
            message.type === "alibabaApiResponse" &&
            message.requestId === requestId
          ) {
            // 请求完成
            browser.runtime.onMessage.removeListener(messageListener);

            // 将AI回复添加到对话历史
            this.messages.push({
              role: "assistant",
              content: message.fullResponse,
            });

            resolve({ answer: message.fullResponse });
          } else if (
            message.type === "alibabaApiError" &&
            message.requestId === requestId
          ) {
            // 请求出错
            browser.runtime.onMessage.removeListener(messageListener);
            reject(new Error(message.error));
          } else if (
            message.type === "alibabaApiStopped" &&
            message.requestId === requestId
          ) {
            // 请求被手动停止 - 确保这里能正确处理
            console.log(
              "收到停止确认消息，部分响应长度:",
              (message.partialResponse || "").length
            );
            browser.runtime.onMessage.removeListener(messageListener);

            // 如果有部分响应，将其添加到对话历史
            if (message.partialResponse) {
              this.messages.push({
                role: "assistant",
                content: message.partialResponse,
              });
              resolve({ answer: message.partialResponse, stopped: true });
            } else {
              // 即使没有部分响应，也要以成功状态结束Promise，避免出现错误提示
              resolve({ answer: "生成已停止", stopped: true });
            }
          }
        };

        // 注册消息监听器
        browser.runtime.onMessage.addListener(messageListener);
      });
    } catch (error) {
      console.error("Error calling Alibaba Cloud API:", error);
      return {
        answer:
          "抱歉，调用API时出现错误。请检查您的网络连接和API配置。" +
          error.message,
      };
    }
  }
}
